var createError = require('http-errors');
var express = require('express');
var multer = require("multer");
var domain = require("domain");
var bodyParse = require('body-parser');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();

var GDloginRouter = require('./routes/GDlogin');
var getCodeRouter = require('./routes/getCode');
var uploadRouter = require('./routes/upload');
var testRouter = require('./routes/test');
var usersRouter = require('./routes/users');
var OEMconfirm_pwdRouter = require('./routes/OEMconfirm_pwd');
var app = express();

app = express();
var session = require('express-session');
const { strict } = require('assert');
app.use(session({
    secret: 'keyboard cat',  //加密session，随便写
    resave: false,   //强制保存session，默认为true，建议设置成false
    saveUninitialized: true, //强制将未初始化的session存储 默认为true，建议设置成true
    cookie: { secure: false }
}));


//开始
// 设置图片存储路径
  var storage = multer.diskStorage({
    destination: function(req, file, cb) {
      cb(null, './uploads');
    },
    filename: function(req, file, cb) {
      cb(null, `${Date.now()}-${file.originalname}`)
    }
  })
  
  // 添加配置文件到muler对象。
  var upload = multer({ storage: storage });
  var imgBaseUrl = '../'
  // bodyParse 用来解析post数据
  app.use(bodyParse.urlencoded({extended:true}));
  app.use(express.static('public'));
  
  // 解决跨域问题
  app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  
    if (req.method == 'OPTIONS') {
      res.send(200); /让options请求快速返回/
    }
    else {
      next();
    }
  });
  
  // 文件上传请求处理，upload.array 支持多文件上传，第二个参数是上传文件数目
  app.post('/uploads/img', upload.array('img', 1), function (req, res,next) {
    // 读取上传的图片信息
    var files = req.files;
    //files.url='http://localhost:3050/routes/uploads/$(files.filename)';
    //console.log(files);
    //res.send(files);
    // 设置返回结果
    var result = {};
    if(!files[0]) {
      result.code = 1;
      res.send('error');
      result.errMsg = '上传失败';
    } else {
      result.code = 0;
      result.data = {
        url: files[0].path
      }
      res.send('success');
      result.errMsg = '上传成功';
    }
    console.log(files);
    res.end(JSON.stringify(result));
  });
//设置用户登录页面路由
/*
  app.post("/loginDo",function(req,res){
    var username = req.query.username;
    var password = req.query.password;
    if(username===usersRouter.username||password===usersRouter.password){
      req.session.username=username; //设置session,表示用户处在的登录状态
      //app.locals对象用于将数据传入所有的渲染ejs模板中，用<%=username%>接收
      req.app.locals["username"]=username;
      res.redirect("/product");
    }else{
      res.send("<script>alert('登陆失败！');location.href='/login';</script>");//用户名或密码不正确

    }
  });
  */
//使用session判断用户是否是登录状态，true则允许访问商品页面/false则跳转到登录页面
/*app.use(function(req,res,next){
  if(req.session.user){
    next();
  }else{
    res.send("<script>alert('您还没有登录，请先登录！');location.href='/login';</script>");
  }
});*/
  //设置商品页面路由，用户若想访问必须通过第三步的拦截
  app.get("/product",function(req,res){
    res.render("product.ejs");//渲染商品页面
  });//退出登录
  app.get("/out",function(req,res){
    req.session.destroy(); //销毁session，退出登录
    res.redirect("/login");
  });
  //用户若没有登录直接访问“商品页面（/product）” ，就会进行拦截提示并跳转到“登录页面（/login）”，只有登录以后才能访问“商品页面”。
//结束

// view engine setup
app.set('views', path.join(__dirname, 'views'));  
app.set('view engine', 'ejs');
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine','html')
//app.engine(ext,'.html',(await import('ejs'))._express)

app.use(bodyParse.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', indexRouter);
app.use('/GDlogin', GDloginRouter);
app.use('/getCode', getCodeRouter);
app.use('/users', usersRouter);
app.use('/test', testRouter);
app.use('/upload', uploadRouter);
app.use('/OEMconfirm_pwd', OEMconfirm_pwdRouter);


//app.use('/uploads', express.static(__dirname + 'routes/uploads'))


app.use(cookieParser());

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
